/* Copyright (c) 2012 Aalto University and University of Helsinki
   MIT License
   see LICENSE.txt for more information
 */

$(function() { // DOCUMENT READY

  // setting the language parameters according to the cookie if found.
  var search_all = readCookie('ONKI_SEARCH_ALL');
  var search_selection = document.getElementById('all-languages-false');

  // taking the url parameters into parts
  var parts = window.location.pathname.split('/'); // splits pathname, e.g.
  // var parts = ($('input#hidden-path')).val().split('/');
  // /onki-light/ysa/en/ and the length is always >= 3
  
  var rest_url = (rest_base_url) ? rest_base_url  : location.protocol + '//' + base_url + 'rest/';
  
  //var lang = (parts.length > 4) ? parts[3] : parts[2]; // initializing
  //var vocab = (parts.length > 4) ? parts[2] : ""; // initializing
  
  var qlang = "&lang="; // initializing qlang, which is 
  
  
  // setting the focus to the search box on default
  $("#search-vocab-parameter").focus();

  // setting the search language parameter according to the all languages
  // radiobutton
  if (search_selection)
    search_selection.checked = true;

  if (search_all == '1') {
    search_selection = document.getElementById('all-languages-true');
    qlang = lang = "";
    if (search_selection)
      search_selection.checked = true;
  }

  $('#all-languages-false').click(function() {
    lang = (parts.length > 4) ? parts[3] : parts[2];
    qlang = "&lang=";
  });

  $('#all-languages-true').click(function() {
    lang = qlang = "";
  });
  
  var termi = "";
  // calls for another function to highlight search term in the labels.
  if (getUrlParams()['q']) {
    localSearchHighlight(decodeURI(getUrlParams()['q'].replace(/\*/g, '')));
    termi = getUrlParams()['q'].replace(/\*/g, '');
  }
  
  var searchInAllLanguages = "";
  if (getUrlParams()['all'] == 1) {
    searchInAllLanguages = "&all=1";
  }
  
  // activates a jquery drop-down plugin for the feedback page.
  $('select#drop-down').selectmenu({
    style : 'dropdown',
    width : 305,
    maxHeight : 400
  });

  // activates the anythingSlider plug-in for the infobox picture slider.
  $('#slider').anythingSlider({
    easing : "easeInOutExpo", // Anything other than "linear" or "swing"
    // requires the easing plugin
    autoPlay : true, // This turns off the entire FUNCTIONALY, not just
    // if it starts running or not.
    delay : 6000, // How long between slide transitions in AutoPlay mode
    startStopped : false, // If autoPlay is on, this can force it to start
    // stopped
    animationTime : 600, // How long the slide transition takes
    hashTags : false, // Should links change the hashtag in the URL?
    buildNavigation : true, // If true, builds and list of anchor links to
    // link to each slide
    pauseOnHover : true, // If true, and autoPlay is enabled, the show
    // will pause on hover
    startText : " ", // Start text
    stopText : " ", // Stop text
    buildArrows : false
  });

  var NoResultsLabel = [ {
    "label" : noResultsTranslation,
    "vocab" : ""
  } ];
  
  if(!getUrlParams()['q'])  $('#search-all-button').attr('disabled', 'disabled'); // initialize disable if search term has been send
  
  $('#search-vocab-parameter').keyup(function() {

    var empty = false;
    $('#search-vocab-parameter').each(function() {
      if ($(this).val().length == 0) {
        empty = true;
      }
    });

    if (empty) {
      $('#search-all-button').attr('disabled', 'disabled');
    } else {
      $('#search-all-button').attr('disabled', false);
    }
  });
  
  // activates jquery autocomplete for the search fields
  var autoC = $("#search-vocab-parameter")
  .autocomplete(
  {
    source : function(request, response) {
      $
      .ajax({
        url : rest_url + 'search?query='
        + request.term + qlang
        + lang + '&vocab=' + vocab,
        dataType : "json",
        success : function(data) {
          if (data.results.length == 0)
            response(NoResultsLabel);

          else {
            response($
              .map(
                data.results
                .filter(function(item) {
                  // either we are performing a local search
                  // or the concept is native to the vocabulary
                  return (vocab != "" || !item.exvocab);
                })
                .slice(
                  0,
                  10),
                function(item) { // slice
                  // limits
                  // results
                  // shown
                  var name = (item.altlabel ? item.altlabel
                    + " \u2192 "
                    + item.label
                    : item.label);
                  item['vocab'] = item.vocab;
                  item['label'] = name;
                  return item;
                }));
          }
        }
      });
    },
    delay : autocomplete_delay, // time (in milliseconds)
    // before autocomplete
    // activates i.e. sends a
    // request to the REST
    // interface
    minLength : autocomplete_activation,

    select : function(event, ui) { // what happens when
      // user clicks/uses
      // autocomplete
      if (ui.item.exvocab)
        var localname = "?uri=" + encodeURIComponent(ui.item.localname);
      else
        var localname = ui.item.localname;

      if (ui.item.label === NoResultsLabel[0].label) {
        event.preventDefault();
        return false;
      } else if ($.inArray('page', parts) != -1)
        location.href = localname;
      else if (parts.length > 4
        && $.inArray($.inArray('index', parts) == -1))
        location.href = '/' + parts[1] + '/'
        + ui.item.vocab + '/' + parts[3]
        + '/page/' + localname;
      else if (parts.length > 4
        && $.inArray('page', parts) == -1)
        location.href = 'page/' + localname;
      else
        location.href = '/' + parts[1] + '/'
        + ui.item.vocab + '/' + lang
        + '/page/' + localname;
    },
    focus : function(event, ui) {
      return false; // Prevent the widget from inserting
    // the value.
    }
  }).data("autocomplete");

  // checks if autocomplete is actually in use to prevent crashing in pages
  // where it is missing
  autoC
  && (autoC._renderItem = function(ul, item) { // just to change
    // the layout in the
    // results list

    if (vocab != "" && !item.exvocab) // local search and native concept
      return $("<li></li>").data("item.autocomplete", item)
      .append(
        '<a style="font-size: 12px;">' + item.label
        + '</a>').appendTo(ul);
    else
      return $("<li></li>")
      .data("item.autocomplete", item)
      .append(
        '<a style="font-size: 12px;"><table style="width:100%;"><tr><td>'
        + item.label
        + '</td><td class="autocomplete-vocab-td">'
        + (item.exvocab ? item.exvocab : item.vocab)
        + '</td></tr></table></a>')
      .appendTo(ul);
  });

  if ($.inArray('search', parts) != -1) { // just to force a max-width for the autocomplete
    // results list
    $(".ui-autocomplete.ui-menu").css('max-width', 634);
  }
  else {
    $("#search-vocab-parameter").bind("autocompleteopen",
      function(event, ui) {
        $(".ui-autocomplete.ui-menu").css('max-width', 663);
      });
  }
  /*
  if (parts.length < 5) // autofocus if no vocab has been selected
    $("#search-vocab-parameter").autocomplete("option", "autoFocus", true);
*/
  $("button#send-feedback").button({
    icons : {
      primary : "ui-icon-mail-closed"
    }
  });

  // Some form validation for the feedback form
  $("#send-feedback")
  .click(
    function() {
      $(".error").remove();
      var emailMessageVal = $("#message").val();
        
      if (emailMessageVal == '') {
        $("#message")
        .after(
          '<ul class="error"><li><span class="errors">Value is required and can\'t be empty</ul></li></span>');
        return false;
      }
      return true;
    });

  // activation and initialisation for the jquery waypoints plug-in used for
  // the scrollable search results.
  var $loading = $("<div class='loading-text'><p class='conceptlabel'>" + loading_text + "&hellip;<span class='spinner'/></p></div>"), $footer = $('footer'), opts = {
    offset : '100%'
  };
  var currentlyLoading = false;
  var offcount = 1;
  var number_of_hits = document.getElementsByClassName("concept-hit").length;
  var $ready = $("<div class='loading-text'><p class='conceptlabel'>" + results + " " + number_of_hits + " " + results_disp +"</p></div>");
  var $displayed = $("<div class='result-count-text'><p class='conceptlabel'>" + waypoints_disp + number_of_hits + waypoints_res + "</p></div>");
  
  if (parts[parts.length-1].indexOf('search') != -1 && number_of_hits != 0) { // if we are in the search page with some results
    if (number_of_hits < waypoint_results * offcount) { 
      $('#vocab-content').append($ready);
    }
    else {
      $('#vocab-content').prepend($displayed);
      $footer.waypoint(function(event, direction) {
        if (currentlyLoading == false) {
          currentlyLoading = true;
          $displayed.detach();
          $footer.waypoint('remove');
          if (number_of_hits >= waypoint_results * offcount)
            $('#vocab-content').append($loading);

          $.ajax({
            url : window.location.pathname + '?q=' + termi + qlang
            + lang + '&vocab=' + vocab + '&offset=' + offcount
            * waypoint_results + searchInAllLanguages,
            success : function(data) {
              currentlyLoading = false;
              $loading.detach();
              if (data == "") {
                $('#vocab-content').append($ready);
                return false;
              }
              $('#vocab-content').append(data);
              $footer.waypoint(opts);
              number_of_hits = document.getElementsByClassName("concept-hit").length;
              $ready = $("<div class='loading-text'><p class='conceptlabel'>" + results + " " + number_of_hits + " " + results_disp +"</p></div>");
              offcount++;
              if (getUrlParams()['q'])
                localSearchHighlight(decodeURI(getUrlParams()['q']
                  .replace(/\*/g, "")));
              if (number_of_hits < waypoint_results * offcount) {
                $('#vocab-content').append($ready);
                currentlyLoading = true; // fixes problem where the script wouldn't realize that it had already displayed all the results
              }
              $displayed = $("<div class='result-count-text'><p class='conceptlabel'>" + waypoints_disp + number_of_hits + waypoints_res + "</p></div>");
              $('#vocab-content').prepend($displayed);
              return false;
            }
          });
        }

      }
      , opts);
    }
  }
});
